package com.cat.chapter051;

/**
 * @author cat
 * @description https://leetcode.cn/problems/split-array-largest-sum/
 * @create 2025/7/22 09:37
 * @since JDK17
 */

public class Solution02 {
    public boolean check(int[] nums, int k, int target) {
        int sum = 0, cnt = 0;
        for (int num : nums) {
            sum += num;
            if (sum > target) {
                sum = num;
                cnt++;
            }
        }
        return cnt <= k;
    }

    public int splitArray(int[] nums, int k) {
        int l = 0, r = 0, mid;
        for (int num : nums) {
            r += num;
        }

        while (l + 1 < r) {
            mid = l + (r - l) / 2;
            if (check(nums, k, mid)) {
                r = mid;
            } else {
                l = mid;
            }
        }

        return r;
    }
}
